﻿/*Project
 *  Name: Regular delete folder
 *  Purpose: Regularly delete files a few days ago
 * Author
 *  Name: Wynter Xu
 *  Date: 2018/11/5
 */

using System;
using System.Text;
using System.IO;
using System.Windows.Forms;
using System.Drawing;

namespace RegularDeleteFolder
{
    public partial class MainForm : Form
    {
        #region 全局变量
        string needDelFolderPath;
        int hourStartTime = 3;
        int agoDays = 7;
        bool isExecutingFlag = false;
        #endregion

        public MainForm()
        {
            InitializeComponent();
            displayIsExecute();
            this.timer.Interval = 10 * 60 * 1000;//定时器的刷新频率为1小时一次
            this.button_cancel.Enabled = false;
            this.mainNotifyIcon.Visible = false;
        }

        
        private bool deleteFolder(string path, int days)
        {
            bool result = false;

            if (!Directory.Exists(path)) return false;

            writeLog("——————————开始对文件夹 【" + path + "】进行操作——————————");

            var filesGroup = Directory.GetFiles(path);
            foreach (var file in filesGroup)
            {
                FileInfo fileInfo = new FileInfo(file);
                if (fileInfo.Attributes.ToString().IndexOf("ReadOnly") != -1)
                {
                    fileInfo.Attributes = FileAttributes.Normal;
                }
                File.Delete(file);
                writeLog("文件 【" + file + "】 已删除");
            }

            var directoryGroup = Directory.GetDirectories(path);
            foreach (var directory in directoryGroup)
            {
                DirectoryInfo dirinfo = new DirectoryInfo(directory);
                if (dirinfo.CreationTime.Subtract(DateTime.Now).Days >= days)
                    Directory.Delete(directory, true);
                writeLog("文件夹 【" + directory + "】 已删除");
            }
       
            writeLog("——————————结束对文件夹 【" + path + "】的操作——————————");
            return result;
        }

        private bool IsExist(string path)
        {
            bool result = false;

            if (Directory.Exists(path))
            {
                result = true;
            }
            else
            {
                result = false;
                MessageBox.Show("文件夹不存在，请重新输入");//调试用
                this.textBox_delFolderPath.Text = string.Empty;
                this.textBox_delFolderPath.Focus();
            }

            return result;
        }

        private void button_searchFolder_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog dilog = new FolderBrowserDialog();
            dilog.Description = "请选择文件夹";
            if (dilog.ShowDialog() == DialogResult.OK)
            {
                needDelFolderPath = dilog.SelectedPath;
                this.textBox_delFolderPath.Text = dilog.SelectedPath;
            }
        }

        private void button_Execute_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(this.textBox_delFolderPath.Text.Trim()))
            {
                this.timer.Enabled = true;
                needDelFolderPath = this.textBox_delFolderPath.Text.Trim();

                isExecutingFlag = true;
                displayIsExecute();
                this.button_cancel.Enabled = true;
                this.button_Execute.Enabled = false;
                this.button_executeNow.Enabled = true;
                this.dislayTray();
            }
            else
            {
                MessageBox.Show("请填入需要被删除的文件夹路径");
            }
        }
        /// <summary>
        /// 显示托盘，隐藏窗口和状态栏图标
        /// </summary>
        private void dislayTray()
        {
            this.WindowState = FormWindowState.Minimized;
            this.ShowInTaskbar = false;
            this.Hide();
            this.mainNotifyIcon.Visible = true;
        }
        /// <summary>
        /// 显示窗口，隐藏托盘
        /// </summary>
        private void displayForm()
        {
            this.Visible = true;
            this.WindowState = FormWindowState.Normal;
            this.Activate();
            this.ShowInTaskbar = true;
            this.mainNotifyIcon.Visible = false;
        }
        private void button_cancel_Click(object sender, EventArgs e)
        {
            this.timer.Enabled = false;
            this.button_Execute.Enabled = true;
            this.button_cancel.Enabled = false;
            isExecutingFlag = false;
            displayIsExecute();
        }

        private void button_executeNow_Click(object sender, EventArgs e)
        {
            needDelFolderPath = this.textBox_delFolderPath.Text.Trim();
            if (IsExist(needDelFolderPath))
            {
                deleteFolder(needDelFolderPath, 0);
                MessageBox.Show("文件夹删除成功!");
            }
        }

        private void button_Exit_Click(object sender, EventArgs e)
        {
            this.mainNotifyIcon.Visible = false;
            this.mainNotifyIcon.Dispose();

            System.Environment.Exit(0);//彻底退出程序
        }


        private void comboBox_selectTimeHour_TextChanged(object sender, EventArgs e)
        {
            var value = this.comboBox_selectTimeHour.Text.Trim();
            if (string.IsNullOrEmpty(value)) return;
            hourStartTime = checkHourType(value);
        }
        private int checkHourType(string strHour)
        {
            int result = 0;
            if (int.TryParse(strHour, out result))
            {
                if (result >= 0 && result < 24)
                {
                    return result;
                }
                else
                {
                    MessageBox.Show("请输入0--23之间的整数");
                }
            }
            else
            {
                MessageBox.Show("请输入整数");
            }
            return result;
        }

        private void textBox_agoDays_TextChanged(object sender, EventArgs e)
        {
            var value = this.textBox_agoDays.Text.Trim();
            if (String.IsNullOrEmpty(value)) return;
            
            if (!int.TryParse(value, out agoDays))
            {
                MessageBox.Show("请输入正整数！");
                this.textBox_agoDays.Text = string.Empty;
            }
        }
        /// <summary>
        /// 在特定的小时，执行删除操作
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void timer_Tick(object sender, EventArgs e)
        {
            if (DateTime.Now.Hour == hourStartTime)
            {
                deleteFolder(needDelFolderPath, agoDays);
            }
        }

        private void writeLog(string msg)
        {
            string logDirPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "log");
            if (!Directory.Exists(logDirPath))
            {
                Directory.CreateDirectory(logDirPath);
            }
            string logFilePath = Path.Combine(logDirPath, "DeleteLog.log");
            if (!File.Exists(logFilePath))
            {
                File.Create(logFilePath).Close();
            }
            using (FileStream stream = new FileStream(logFilePath, FileMode.Append, FileAccess.Write, FileShare.Read))
            {
                using (StreamWriter writer = new StreamWriter(stream, Encoding.UTF8))
                {
                    writer.WriteLine(DateTime.Now.ToString() + " : " + msg);
                    writer.Flush();
                }

            }
        }
        /// <summary>
        /// 最小化操作，隐藏到托盘
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MainForm_SizeChanged(object sender, EventArgs e)
        {
            if (this.WindowState == FormWindowState.Minimized)
            {
                dislayTray();
            }
        }
        /// <summary>
        /// 双击窗口，则显示操作窗口
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void mainNotifyIcon_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            if (this.WindowState == FormWindowState.Minimized)
            {
                displayForm();
            }
        }

        /// <summary>
        /// 托盘还原按钮操作
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ToolStripMenuItem_DisplayForm_Click(object sender, EventArgs e)
        {
            this.displayForm();
        }
        /// <summary>
        /// 推盘退出按钮操作
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ToolStripMenuItem_Exist_Click(object sender, EventArgs e)
        {
            this.mainNotifyIcon.Visible = false;
            this.mainNotifyIcon.Dispose();
            this.Dispose();
            this.Close();
        }
        /// <summary>
        /// 显示是否已运行的标志
        /// 如果定时器已运行，则显示‘正在运行...’
        /// 反之，显示‘等待运行’
        /// </summary>
        private void displayIsExecute()
        {
            if (isExecutingFlag)
            {
                this.lab_isExecutingFlag.Text = "正在运行...";
                this.lab_isExecutingFlag.ForeColor = Color.Green;
            }
            else
            {
                this.lab_isExecutingFlag.Text = "等待运行";
                this.lab_isExecutingFlag.ForeColor = Color.Olive;
            }
        }
    }
}
